/**
 * Copyright (C) 2018-2020
 * All rights reserved, Designed By www.yixiang.co
 * 注意：
 * 本软件为www.yixiang.co开发研制，未经购买不得使用
 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
 */


package co.yixiang.message.redis.listener;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import co.yixiang.constant.ShopConstants;
import co.yixiang.domain.BaseDomain;
import co.yixiang.enums.BillDetailEnum;
import co.yixiang.enums.BillEnum;
import co.yixiang.enums.ShopCommonEnum;
import co.yixiang.modules.auction.domain.YxAuctionOrder;
import co.yixiang.modules.auction.domain.YxAuctionRecord;
import co.yixiang.modules.auction.domain.YxUserViolateLog;
import co.yixiang.modules.auction.service.YxUserViolateLogService;
import co.yixiang.modules.auction.service.mapper.YxAuctionOrderMapper;
import co.yixiang.modules.auction.service.mapper.YxAuctionRecordMapper;
import co.yixiang.modules.commom.domain.YxAppdict;
import co.yixiang.modules.commom.service.mapper.YxAppdictMapper;
import co.yixiang.modules.user.domain.YxUser;
import co.yixiang.modules.user.domain.YxUserBill;
import co.yixiang.modules.user.service.YxUserBillService;
import co.yixiang.modules.user.service.YxUserService;
import co.yixiang.modules.user.vo.OnlineUser;
import co.yixiang.utils.RandonOrderNoUtil;
import co.yixiang.utils.RedisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * redis过期监听
 * @author hupeng
 * @since 2020-02-27
 */


@Component
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

	@Autowired
	private YxAuctionOrderMapper yxAuctionOrderMapper;
	@Autowired
	private YxAuctionRecordMapper yxAuctionRecordMapper;
	@Autowired
	private YxAppdictMapper yxAppdictMapper;
	@Autowired
	private RedisUtils redisUtil;
	@Autowired
	private YxUserService userService;
	@Autowired
	private YxUserBillService userBillService;
	@Autowired
	private RedisTemplate redisTemplate;
	@Autowired
	private YxUserViolateLogService userViolateLogService;

	public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
		super(listenerContainer);
	}


/**
	 * 针对redis数据失效事件，进行数据处理
	 * @param message
	 * @param pattern
	 */


	@Override
	public void onMessage(Message message, byte[] pattern) {
		// 用户做自己的业务处理即可,注意message.toString()可以获取失效的key
		String expiredKey = message.toString();
		System.out.println("失效key------>"+expiredKey);
		if(expiredKey.contains(ShopConstants.REDIS_AUCTION_ORDER_OUTTIME_UNPAY)){
			String body = expiredKey.replace(ShopConstants.REDIS_AUCTION_ORDER_OUTTIME_UNPAY, "");
			log.info("body:{}",body);
			//拍卖付款时间
			YxAppdict pmfksj=yxAppdictMapper.findAppdictByCode("pmfksj");
			Integer paimaiTime=60;
			if(null !=pmfksj){
				paimaiTime=Integer.parseInt(pmfksj.getMemo());
			}
			String orderId = body;
			YxAuctionOrder yxAuctionOrder=yxAuctionOrderMapper.selectById(orderId);
			YxAuctionRecord yxAuctionRecord=yxAuctionRecordMapper.selectById(yxAuctionOrder.getAuctionRecordId());
			if(null !=yxAuctionOrder){
				Calendar instance = Calendar.getInstance();
				instance.setTime(yxAuctionOrder.getCreateTime());
				instance.add(Calendar.MINUTE,paimaiTime);
				Date newCreateTime = instance.getTime();
				//若为待付款
				if(0==yxAuctionOrder.getStatus()  && newCreateTime.compareTo(new Date())==-1){
					//设为已取消
					yxAuctionOrder.setStatus(5);
					yxAuctionOrder.setIsDel(1);
					if(null !=yxAuctionRecord){
						yxAuctionRecord.setIsBuy(0);
						redisUtil.set("paimai"+yxAuctionRecord.getId(),yxAuctionRecord.getId());
					}
					yxAuctionOrderMapper.updateById(yxAuctionOrder);
					yxAuctionRecordMapper.updateById(yxAuctionRecord);


					//扣除买家金额
					BigDecimal buyUserPrice = new BigDecimal(String.valueOf(redisUtil.get("UserPrice" + yxAuctionOrder.getUserId())));
					BigDecimal buyUserBalance = buyUserPrice.subtract(new BigDecimal("200")).setScale(2 , BigDecimal.ROUND_HALF_UP);
					//TB流水入库
					YxUserBill buyUserBill = YxUserBill.builder()
							.uid(yxAuctionOrder.getUserId())
							.title("未支付，扣除200")
							.linkId(yxAuctionRecord.getId().toString())
							.category(BillDetailEnum.CATEGORY_1.getValue())
							.type(BillDetailEnum.TYPE_11.getValue())
							.number(new BigDecimal("200"))
							.balance(buyUserBalance)
							.mark("未支付，扣除200")
							.status(BillEnum.STATUS_1.getValue())
							.pm(BillEnum.PM_0.getValue())
							.build();
					userBillService.save(buyUserBill);
					//扣除余额
					redisUtil.set("UserPrice"+yxAuctionOrder.getUserId() , buyUserBalance);
					//塞入扣除redis数据 2秒后修改用户余额
					redisUtil.set(yxAuctionOrder.getUserId()+"deduct"+buyUserBalance,yxAuctionRecord.getUserId()+"deduct"+buyUserBalance, 2);

					if (ObjectUtil.isNotEmpty(yxAuctionRecord.getUserId())){
						//卖家余额
						BigDecimal sellBalance = new BigDecimal(String.valueOf(redisUtil.get("UserPrice" + yxAuctionRecord.getUserId())))
								.add(new BigDecimal("100"))
								.setScale(2 , BigDecimal.ROUND_HALF_UP);
						//TB流水入库
						YxUserBill sellBill = YxUserBill.builder()
								.uid(yxAuctionRecord.getUserId())
								.title("用户未支付，补偿100")
								.linkId(yxAuctionRecord.getId().toString())
								.category(BillDetailEnum.CATEGORY_1.getValue())
								.type(BillDetailEnum.TYPE_11.getValue())
								.number(new BigDecimal("100"))
								.balance(sellBalance)
								.mark("用户未支付，补偿100")
								.status(BillEnum.STATUS_1.getValue())
								.pm(BillEnum.PM_1.getValue())
								.build();
						userBillService.save(sellBill);
						//扣除余额
						redisUtil.set("UserPrice"+yxAuctionRecord.getUserId() , sellBalance);
						//塞入扣除redis数据 2秒后修改用户余额
						redisUtil.set(yxAuctionRecord.getUserId()+"deduct"+sellBalance,yxAuctionRecord.getUserId()+"deduct"+sellBalance, 2);
					}

					if (ObjectUtil.isNotEmpty(yxAuctionOrder.getUserId())){
						//将账户冻结
						YxUser user = this.userService.getById(yxAuctionOrder.getUserId());
						user.setIsFreeze(ShopCommonEnum.IS_STATUS_1.getValue());
						List<String> keys = redisUtil.scan(ShopConstants.YSHOP_APP_LOGIN_USER + "*");
						Collections.reverse(keys);
						for (String key : keys) {
							OnlineUser onlineUser = (OnlineUser) redisUtil.get(key);
							if(onlineUser.getUserName().equals(user.getUsername())){
								redisUtil.del(key);
							}
						}
						this.userService.updateById(user);
					}
				}
			}
		}
	}
}


